﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using BotonJXC.DAO;
using BotonJXC.BLL;
using BotonJXC.Util;
using BotonJXC.Entity;
using ComponentFactory.Krypton.Toolkit;

namespace BotonJXC.Forms
{
    public partial class MainFrame : BaseForm
    {
        AuthResBLL _authResBLL = new AuthResBLL();
        IDictionary<int, Form> _toolMenuForms = new Dictionary<int, Form>();
        IList<AuthRes> _leftAuthRes = new List<AuthRes>();
        string _leftAuthResFile = "mytools";
        public MainFrame()
        {
            InitializeComponent();
        }

        ~MainFrame()
        {
            HBHelper.Close();
        }

        const int SC_MINIMIZE = 0xF020;//窗体最小化消息
        const int SC_MAXIMIZE = 0xF030;//窗体最大化消息
        const int SC_NOMAL = 0xF120;//窗体还原消息
        protected override void WndProc(ref Message m)
        {
            //Form mdiForm = this.ActiveMdiChild;
            //if (mdiForm != null)
            //{
            //    if (m.WParam.ToInt32() == SC_MINIMIZE)//点击最小化
            //    {                  
            //        if (mdiForm.WindowState == FormWindowState.Maximized)
            //        {
            //            m.WParam = (IntPtr)SC_MAXIMIZE;
            //            mdiForm.WindowState = FormWindowState.Minimized;
            //        }
            //    }
            //    if (m.WParam.ToInt32() == SC_NOMAL)//点击还原
            //    {
            //        if (mdiForm.WindowState == FormWindowState.Maximized)
            //        {
            //            m.WParam = (IntPtr)SC_MAXIMIZE;
            //            mdiForm.WindowState = FormWindowState.Normal;
            //        }
            //    }
            //}
            base.WndProc(ref m);
        }

        private void rOrbMIExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MainFrame_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                ShowLoginForm();
                kryptonHeaderGroup1.Text = "我的工具箱";
            }
        }

        public void LoadMainMenu()
        {
            IList<AuthRes> authRes = _authResBLL.FindByUserId(LoginForm.UserId);
            SysContext.CurrentUserResAuth = authRes;
            TreeDataNode<AuthRes> menuTree = _authResBLL.ToTree(authRes);
            foreach (TreeDataNode<AuthRes> mar in menuTree)
            {
                if (mar != null)
                {
                    RibbonTab rTab = CreateRibbonTab(mar);
                    foreach (TreeDataNode<AuthRes> mar2 in mar)
                    {
                        if (mar2 != null)
                        {
                            RibbonPanel rPanel = CreateRibbonPanel(rTab, mar2);
                            foreach (TreeDataNode<AuthRes> mar3 in mar2)
                            {
                                if (mar3 != null)
                                {
                                    CreateRibbonButton(rPanel, mar3);
                                }
                            }
                        }
                    }
                }
            }
            this.Refresh();
        }

        private RibbonTab CreateRibbonTab(TreeDataNode<AuthRes> node)
        {
            RibbonTab rTab = new RibbonTab();
            rTab.Text = node.Data.AuthResName;
            ribbonMain.Tabs.Add(rTab);
            return rTab;
        }

        private RibbonPanel CreateRibbonPanel(RibbonTab rTab, TreeDataNode<AuthRes> node)
        {
            RibbonPanel rPanel = new RibbonPanel(node.Data.AuthResName);
            rPanel.ButtonMoreVisible = false;
            rTab.Panels.Add(rPanel);
            return rPanel;
        }
        private void CreateRibbonButton(RibbonPanel panel, TreeDataNode<AuthRes> node)
        {
            RibbonButton rBtn = new RibbonButton();
            rBtn.AltKey = null;
            rBtn.DropDownArrowDirection = System.Windows.Forms.RibbonArrowDirection.Down;
            rBtn.DropDownArrowSize = new System.Drawing.Size(5, 3);
            rBtn.Image = global::BotonJXC.Forms.Properties.Resources.find32;
            rBtn.SmallImage = global::BotonJXC.Forms.Properties.Resources.find32;
            rBtn.Style = System.Windows.Forms.RibbonButtonStyle.Normal;
            rBtn.Tag = node.Data;
            rBtn.Text = node.Data.AuthResName;
            rBtn.ToolTip = null;
            rBtn.ToolTipImage = null;
            rBtn.ToolTipTitle = null;
            rBtn.MouseDown += new MouseEventHandler(rBtn_MouseDown);
            panel.Items.Add(rBtn);
        }

        void rBtn_MouseDown(object sender, MouseEventArgs e)
        {
            RibbonButton button = (RibbonButton)sender;
            DragDropEffects dropEffect = button.DoDragDrop(button, DragDropEffects.Copy | DragDropEffects.Move);
            if (dropEffect == DragDropEffects.None)
            {
                AuthRes authRes = button.Tag as AuthRes;
                ShowFormByMenu(authRes);
            }
        }

        void ShowFormByMenu(AuthRes authRes)
        {
            if (authRes.AuthResType == 2)
            {
                Form form = null;
                if (_toolMenuForms.TryGetValue(authRes.AuthResId, out form))
                {
                    if (form.IsDisposed)
                    {
                        form = CreateToolMenuForm(authRes.AuthResSn, authRes.AuthResArgs);
                        if (form != null)
                            _toolMenuForms[authRes.AuthResId] = form;
                    }
                }
                else
                {
                    form = CreateToolMenuForm(authRes.AuthResSn, authRes.AuthResArgs);
                    if (form != null)
                        _toolMenuForms.Add(authRes.AuthResId, form);
                }

                if (form != null)
                {
                    Form mdiForm = this.ActiveMdiChild;
                    if (mdiForm != null && mdiForm != form && !mdiForm.IsDisposed)
                    {
                        mdiForm.Close();
                    }
                    form.WindowState = FormWindowState.Maximized;
                    form.StartPosition = FormStartPosition.CenterParent;
                    form.MdiParent = this;
                    form.Show();
                }
            }
        }

        Form CreateToolMenuForm(string formName, string tag) {
            string cls = "BotonJXC.Forms." + formName;
            Form form = (Form)this.GetType().Assembly.CreateInstance(cls);
            if (form == null)
            {
                return null;
            }
            else
            {
                form.Tag = tag;
                return form;
            }
        }
        private void riBtnLogin_Click(object sender, EventArgs e)
        {
            ShowLoginForm();
        }

        private void ShowLoginForm()
        {
            LoginForm lf = new LoginForm();
            lf.StartPosition = FormStartPosition.CenterParent;
            lf.MdiParent = this;
            lf.Show();
        }

        public void SetCurrentUserInfo(Account user)
        {
            tsslUserInfo.Text = string.Format("当前用户：{0} {1} {2}", "", user.Department.DepName, user.Realname);
        }

        private void MainFrame_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定要退出此系统码?", "退出确认", MessageBoxButtons.OKCancel);
            if (dr != System.Windows.Forms.DialogResult.OK)
            {
                e.Cancel = true;
            }
        }

        private void kryptonHeaderGroup1_Panel_DragEnter(object sender, DragEventArgs e)
        {
            //当Button被拖拽到WinForm上时候，鼠标效果出现
            if ((e.Data.GetDataPresent(typeof(RibbonButton))))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void kryptonHeaderGroup1_Panel_DragDrop(object sender, DragEventArgs e)
        {
            RibbonButton btn = e.Data.GetData(typeof(RibbonButton)) as RibbonButton;
            AppendLeftButton(btn.Tag as AuthRes);
        }

        void AppendLeftButton(AuthRes authRes)
        {
            bool create = true;
            foreach (AuthRes r in _leftAuthRes)
            {
                if (r.AuthResId == authRes.AuthResId)
                {
                    create = false;
                    break;
                }
            }
            if (create)
            {
                _leftAuthRes.Add(authRes);
                KryptonButton btn = CreateLeftButton(authRes);
                btn.Visible = true;
                //btn.Size = new System.Drawing.Size(120, 50);
                btn.Location = new Point(11, 10 + (_leftAuthRes.Count - 1) * 30);
                kryptonHeaderGroup1.Panel.Controls.Add(btn);
                Utils.SerializeList<AuthRes>(GetLeftMenuFile(), _leftAuthRes);
            }
        }
        string GetLeftMenuFile()
        {
            return AppDomain.CurrentDomain.BaseDirectory + _leftAuthResFile + LoginForm.Account.UserId;
        }

        public void LoadLeftMenus()
        {
            _leftAuthRes = Utils.DeserializeList<AuthRes>(GetLeftMenuFile());
            for (int i = 0; i < _leftAuthRes.Count; i++)
            {
                KryptonButton btn = CreateLeftButton(_leftAuthRes[i]);
                btn.Location = new Point(11, 10 + i * 30);
                kryptonHeaderGroup1.Panel.Controls.Add(btn);
            }
        }

        KryptonButton CreateLeftButton(AuthRes authRes)
        {
            KryptonButton btn = new KryptonButton();
            btn.AutoSize = true;
            btn.TabIndex = 0;
            btn.Values.Image = global::BotonJXC.Forms.Properties.Resources.goto16;
            btn.Values.Text = authRes.AuthResName;
            btn.Tag = authRes;
            btn.ButtonStyle = ButtonStyle.NavigatorStack;
            btn.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
            btn.MouseDown += new MouseEventHandler(btn_MouseDown);
            if (btn.Width < 120)
                btn.Width = 120;
            return btn;
        }

        void btn_MouseDown(object sender, MouseEventArgs e)
        {
            KryptonButton button = (KryptonButton)sender;
            DragDropEffects dropEffect = button.DoDragDrop(button, DragDropEffects.Copy | DragDropEffects.Move);
            if (dropEffect == DragDropEffects.None)
            {
                AuthRes authRes = button.Tag as AuthRes;
                ShowFormByMenu(authRes);
            }
        }
    }
}
